package com.jrapider.compent.dict;

import com.jrapider.FreemarkerConfig;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Auther: hxs
 * @Date: 2019/1/1
 * @Description:
 */
@Component("dict")
@Log4j2
public class DictTemplateDirectiveModel implements TemplateDirectiveModel {
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
        log.info(params);
        String code = FreemarkerConfig.transString(params.get("code"));
        List<DictData> dictDataList = DictTranslater.getDict(code);
        env.setVariable("dicts",getBeansWrapper().wrap(dictDataList));
        body.render(env.getOut());

    }
    public static BeansWrapper getBeansWrapper(){
        BeansWrapper beansWrapper =
                new BeansWrapperBuilder(Configuration.VERSION_2_3_28).build();
        return beansWrapper;
    }
}
